#!/usr/bin/env python
# -*- coding:utf-8 -*-
########被监控机，发布者########
from main import RedisHelper
import time
import redis
import os
import json
import action

redis_server='192.168.136.8'
redis_port=6379
myip=os.popen("ifconfig |awk 'NR==2 {print $2}'").read().strip()

def monitor():
    #从redis获取模板，执行命令。myip:{'cpu':'get_load_avg','process':'get_pro_num'}
    #
    r=redis.Redis(host=redis_server,port=redis_port)
    module=json.loads(r.get(myip))    #linux上不会报错，windows报错
    cpu_action=module['cpu']
    cpu_func=getattr(action,cpu_action)
    pro_action=module['process']
    pro_func=getattr(action,pro_action)
    msg={'ip':myip,'cpu':cpu_func(),'process':pro_func()}
    return json.dumps(msg)

if __name__ == '__main__':
    p=RedisHelper()
    print "starting monitor,press ctrl+c to exit!"
    while True:
        try:
            monitor_data=monitor()
            p.pub(monitor_data)
            time.sleep(10)
        except KeyboardInterrupt:
            break

